import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:video_player/video_player.dart';
import 'package:tiktokadult/hj_page/home_business/tag/video_tag_page.dart';
import 'package:tiktokadult/hj_page/video/view/detail_top_right_view.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import '../../../../alert_business/video/share_video_dialog.dart';
import '../../../../alert_business/video/video_buy_bottom_sheet.dart';
import '../../../../config/address.dart';
import '../../../../hj_model/splash/watch_count_model.dart';
import '../../../../hj_utils/free_play_count_manager.dart';
import '../../../../routers/jump_router.dart';
import '../../../../tools_base/global_store/store.dart';
import '../../../darkweb/widget/shrink_wrap.dart';
import '../../../pre_sale/pre_sale_provider.dart';
import '../../../../alert_business/video/video_line_menu_alert.dart';

/// 首页搜索按钮视图
class ShortLeftItem extends StatefulWidget {
  final VideoModel? videoModel;

  /// 是否显示视频发布时间，目前只有（推荐）不显示
  final bool isDisplayTime;
  final VoidCallback? onBuy;
  final VideoPlayerController? controller;
  final WatchCount? watchCount;

  const ShortLeftItem(
    this.videoModel,
    this.controller, {
    Key? key,
    this.isDisplayTime = false,
    this.onBuy,
    this.watchCount,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ShortLeftItemState();
  }
}

class _ShortLeftItemState extends State<ShortLeftItem> {
  bool visible = true;
  bool isNewUser = false;

  bool get isFollow => widget.videoModel?.publisher?.hasFollowed ?? false;

  bool get isMy => globalStore.isMe(widget.videoModel?.publisher?.uid);

  double get gapValue => 12;

  LongVideStatus get videoStatus => longVideoStatusDesc(widget.videoModel);

  /// 金币视频需要购买的显示
  bool get isShowCoinBuy {
    return false;
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(left: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          _buildAuthorItem(),
          _buildTitleItem(),
          //_buildStaticCount(),
          _buildTagItem(),
          _buildBuyItem(),
          _buildVipItem(),
          // ShortNewerTimerVip(controller: widget.controller),
        ],
      ),
    );
  }

  Widget _buildAuthorItem() {
    return Container(
      padding: EdgeInsets.only(top: gapValue),
      child: Row(
        children: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.deferToChild,
            onTap: () {
              widget.controller?.pause();
              pushToPersonCenter(widget.videoModel?.publisher?.uid);
            },
            child: Row(
              children: [
                Text(
                  "@${widget.videoModel?.publisher?.name ?? ""}",
                  maxLines: 1,
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.w500,
                    height: 22/16,
                  ),
                ),
                4.sizeBoxW,
                Image.asset("vip_user.webp".videoPath, width: 16),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTitleItem() {
    if ((widget.videoModel?.title?.trim() ?? "").isEmpty) {
      return SizedBox();
    }
    return Container(
      padding: EdgeInsets.only(top: gapValue),
      child: Text(
        widget.videoModel?.title?.trim() ?? "",
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: Colors.white,
          fontSize: 12,
          shadows: [
            Shadow(
              color: Colors.black.withOpacity(0.05),
              offset: const Offset(1, 1),
              blurRadius: 5,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBuyItem() {
    /// 有价格 且 不是自己的作品
    if (globalStore.isMe(widget.videoModel?.publisher?.uid)) {
      return const SizedBox();
    }
    if (widget.videoModel?.freeArea == true) {
      return const SizedBox();
    }
    if (widget.videoModel?.isCoinVideo() != true) {
      return const SizedBox();
    }
    if (widget.videoModel?.vidStatus?.hasPaid == true) {
      return Container(
        margin: EdgeInsets.only(top: gapValue),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(3),
          color: Color(0xffFF9000),
        ),
        child: const Text(
          "已购买",
          style: TextStyle(
            color: Color(0xff292929),
            fontSize: 12,
          ),
        ),
      );
    }
    if (videoStatus.statusDesc == "已享金币视频免费特权") {
      return Container(
        margin: EdgeInsets.only(top: gapValue),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(3)),
          color: Color(0x99000000),
        ),
        child: Text(
          videoStatus.statusDesc,
          style: TextStyle(color: Colors.white, fontSize: 12),
        ),
      );
    }
    if ((widget.watchCount?.coinWatchCount ?? -1) >= 0) {
      return Container(
        margin: EdgeInsets.only(top: gapValue),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(3)),
          color: Color(0x99000000),
        ),
        child: Text(
          "免费金币观影数剩余: ${widget.watchCount?.coinWatchCount}次",
          style: TextStyle(color: Colors.white, fontSize: 12),
        ),
      );
    }
    return Container(
      margin: EdgeInsets.only(top: gapValue),
      child: GestureDetector(
        onTap: () async {
          widget.controller?.pause();
          widget.onBuy?.call();
          // bool hasPresaleActivity = presaleProvider.isOpen && !presaleProvider.isPayAll();
          // var result = await Get.bottomSheet(VideoBuyBottomSheet(videoM: widget.videoModel!, presale: hasPresaleActivity));
          // if (result == true) {
          //   widget.videoModel?.vidStatus?.hasPaid = true;
          //   setState(() {});
          // }
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
          decoration: BoxDecoration(
            color: Color(0xffFF9000),
            borderRadius: BorderRadius.circular(3),
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset("coin_small.webp".videoPath, width: 18),
              1.sizeBoxW,
              Text(
                "${widget.videoModel?.coins}金币 解锁",
                style: TextStyle(
                  color: Color(0xff292929),
                  fontSize: 12,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildVipItem() {
    if (globalStore.isMe(widget.videoModel?.publisher?.uid)) {
      return const SizedBox();
    }
    if (widget.videoModel?.freeArea == true) {
      return const SizedBox();
    }
    if (widget.videoModel?.isCoinVideo() == true) {
      return const SizedBox();
    }
    int watchValue = widget.watchCount?.watchCount ?? 0;
    if (FreePlayCountManager().canFreePlay(widget.videoModel) && watchValue < 0) {
      // 免费观看次数内观看的视频, 重新观看,视频是可以观看, 但次数小于0时不显示
      return SizedBox();
    }

    if (videoStatus.statusDesc == "已享VIP免费特权") {
      return Container(
        margin: EdgeInsets.only(top: gapValue),
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(3)),
          color: Color(0x99000000),
        ),
        child: Text(
          "已享VIP免费特权",
          style: TextStyle(color: Colors.white, fontSize: 12),
        ),
      );
    }

    bool isShowFreeCount = (watchValue >= 0);
    return InkWell(
      onTap: () async {
        if (watchValue > 0) return;
        bool isPlay = widget.controller?.value.isPlaying ?? false;
        widget.controller?.pause();
        await jumpToWalletPage();
        await globalStore.refreshWallet();
        if (isPlay) {
          widget.controller?.play();
        }
      },
      child: Container(
        margin: EdgeInsets.only(top: gapValue),
        padding: const EdgeInsets.fromLTRB(10, 4, 10, 4),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(30),
          gradient: LinearGradient(
            colors: [
              isShowFreeCount ? Color(0xffFF1B69) : Color(0xffFF1B69),
              isShowFreeCount ? Color(0xffF83390) : Color(0xffF83390),
            ],
          ),
        ),
        child: Text(
          isShowFreeCount ? "免费视频剩余${watchValue + 1}次" : "开通会员 畅享完整版",
          style: TextStyle(color: isShowFreeCount ? Colors.white: Colors.white, fontSize: 12),
        ),
      ),
    );
  }

  Widget _buildTagItem() {
    if (widget.videoModel?.tags?.isNotEmpty == true) {
      return Container(
        padding: EdgeInsets.only(top: gapValue),
        child: ShrinkWrap(
          spacing: 0,
          runSpacing: 6,
          maxLines: 1,
          children: widget.videoModel?.tags
                  ?.map((e) => InkWell(
                        onTap: () {
                          widget.controller?.pause();
                          Get.to(VideoTagPage(e, isShortStyle: true), preventDuplicates: true);
                        },
                        child: Container(
                          padding: EdgeInsets.fromLTRB(8, 3, 8, 3),
                          margin: EdgeInsets.only(right: 6),
                          child: Text(
                            "#${e.name}",
                            style: TextStyle(
                              color: Color(0xffF0C731),
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ))
                  .toList() ??
              [],
        ),
      );
    }
    return const SizedBox();
  }

  Widget _buildStaticCount() {
    return Container(
        padding: EdgeInsets.only(top: gapValue),
        child: Row(
          children: [
            _buildItemImgText("play_eye.webp".videoPath, widget.videoModel?.playCount?.humanizeFormat),
            12.sizeBoxW,
            Container(height: 12, color: Color(0x1AFFFFFF), width: 1),
            12.sizeBoxW,
            _buildItemImgText("play_time.webp".videoPath, widget.videoModel?.playTime?.timeMSFormat),
            12.sizeBoxW,
            Container(height: 12, color: Color(0x1AFFFFFF), width: 1),
            12.sizeBoxW,
            InkWell(
              onTap: () async {
                await VideoLineMenuAlert.show();
                setState(() {});
              },
              child: _buildItemImgText("play_line.webp".videoPath, Address.currentDomain?.desc),
            ),
          ],
        ));
  }

  Widget _buildItemImgText(String imagePath, String? title) {
    return Row(
      children: [
        Image.asset(
          imagePath,
          width: 16,
          height: 16,
        ),
        2.sizeBoxW,
        Text(
          title ?? "",
          style: TextStyle(
            color: Colors.white.withOpacity(0.45),
            fontSize: 12,
          ),
        )
      ],
    );
  }

  void onShareEvent() async {
    Get.back();
    Get.dialog(ShareVideoDialog(videoModel: widget.videoModel));
  }
}
